﻿var BankValidationClientSideHide = false;
var PageNumber = 1;
var IsSearchView = false;
var IsDeleteView = false;
var BankIDView = 0;
var SelectedCountryID = null;
var Phone800 = null;
var PhoneNumber = null;
var FaxNumber = null;
var BankAutoComElem = null;
var BankAutoComElemVal = null;
var BankTimerId = null;
$(document).ready(function () {
    var path = window.location.pathname;
    if (path.indexOf("SetupBank") != -1) {
        $.validator.addMethod("SetupBankRequireds", $.validator.methods.required, Messages["SetupBankRequireds"]);
        $.validator.addMethod("SetupBankMaxLength20", $.validator.methods.maxlength, Messages["SetupBankMaxLength20"]);
        $.validator.addMethod("SetupBankMaxLength50", $.validator.methods.maxlength, Messages["SetupBankMaxLength50"]);
        $.validator.addMethod("SetupBankMaxLength100", $.validator.methods.maxlength, Messages["SetupBankMaxLength100"]);
        $.validator.addClassRules({
            Required: {
                SetupBankRequireds: true,
            },
            MaxLength100: {
                SetupBankMaxLength100: 100,
            },
            MaxLength50: {
                SetupBankMaxLength50: 50,
            },
            MaxLength20: {
                SetupBankMaxLength20: 20,
            },
        });

        $('#LoadBankDetailsForm').validate();
        LoadBankGrid();
    }
});
$(document).on('change', '.BankDetailsElementChange', function () {
    if (!$('#BankDetailsSaveBtn').hasClass("disabled")) {
        $('#BankDetailsSaveBtn').addClass('BackColorRed');
    }
});
function DeleteBank(BankID) {
    jConfirm('Are you sure you want to delete this Bank?', 'Warning!', function (retVal) {
        if (retVal == true) {
            BankIDView = BankID;
            IsDeleteView = true;
            LoadBankGrid();
        }
    });
}
function ShowBank(BankID)
{
    ShowBankDetails(BankID)
}
function ShowBankDetails(BankID) {
    $.ajax({
        url: urls["SetupLoadBankDetails"],
        data: { 'BankID': BankID },
        type: 'GET',
        success: function (data) {
            $("#BanksDetailsDiv").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            IsDeleteView = false;
            ShowBankDetailPopUp("BanksDetailsDiv");
        }
    });
}
$(document).on('click', '#BankMoreBtn', function () {
    PageNumber = PageNumber + 1;
    IsDeleteView = false;
    LoadBankGrid()
});
$(document).on('click', '#BankSearchBtn', function () {
    IsDeleteView = false;
    IsSearchView = true;
    LoadBankGrid()
});
function ShowBankDetailPopUp(PopUpDiv) {
    $.colorbox({
        width: "1000px",
        height: "515px",
        inline: true,
        href: "#"+PopUpDiv,
        onComplete: function () {
            SelectedCountryID = $("#SelectedCountryID").val();
            Phone800 = $("#Phone800").val();
            PhoneNumber = $("#PhoneNumber").val();
            FaxNumber = $("#FaxNumber").val();
            FormattedPhoneNumbers(SelectedCountryID);
            $(".phone").mask("(###) ###-####");
            $(".phoneUSACAN").mask("+1 (###) ###-####");
            $(".phoneTR").mask("+90 (###) ###-####");
            $(".phoneFR").mask("+33 (#) ##-##-##-##");
            $(".phoneBEL").mask("+32 (#) ###-##-##");
            $(".phoneSWI").mask("+41 (##) ###-####");
            $(".phoneTS").mask("+216 (##) ###-###");
            $(".phoneALG").mask("+213 (##) ###-####");
            $(".phoneMA").mask("+212 (##) ###-####");
            $(".PostalCode").mask("#####-####");
            $("#" + PopUpDiv).show(); 
        },
        onClosed: function () {
            $("#" + PopUpDiv).hide();
        }
    });
}
$(document).on('click', '#BankDetailsSaveBtn', function () {
    var $form = $('#LoadBankDetailsForm');
    if ($form.valid()) {
        BankValidationClientSideHide = false;
        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
            data: $form.serialize(),
            beforeSend: function (xhr) {
                xhr.overrideMimeType('text/plain; charset=x-user-defined');
            },
            success: function (data) {
                if (data.indexOf("Error") != -1)
                    jAlert(data, "Error");
            },
            error: function (xhr) {
                jAlert(xhr.statusText, "Error");
            },
            complete: function () {
                if ($("#BankID").val() == 0) {
                    $('#BankDetailsSaveBtn').removeClass('BackColorRed')
                    jAlert("Data SuccessFully Saved:", "Successful");
                    $('#cboxClose').click();
                    LoadBankGrid();
                }
                else {
                    $('#BankDetailsSaveBtn').removeClass('BackColorRed')
                    jAlert("Data SuccessFully Saved:", "Successful");
                    ShowBankDetails($("#BankID").val())
                }
                IsDeleteView = false;
            }
        });
    }
    else
        BankValidationClientSideHide = true;
});
function LoadBankGrid()
{
    var SetupBanksGridViewModel = {
        BankNameText: $("#BankNameText").val(),
        CitySearchText: $("#CitySearchText").val(),
        BankCodeText: $("#BankCodeText").val(),
        PageNum: parseInt(PageNumber),
        IsSearch: IsSearchView,
        IsDelete: IsDeleteView,
        BankID: parseInt(BankIDView),
        IsActiveSearch: $("#IsActiveSearch").val(),
    };
    
    var DTO = JSON.stringify(SetupBanksGridViewModel);
    $.ajax({
        url: urls["SetupLoadBanksGrid"],
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: DTO,
        success: function (data) {
            $("#SetupBankGrid").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {

        }
    });
}
$(document).on('change', '.CountryDrop', function () {
    FormattedPhoneNumbers($(this).val());
    if ($(this).val() === "") {
        $("#StateDiv").hide();
        $("#CityDiv").hide();
        $("#StateDivChange").show();
        $("#CityDivChange").show();
    }
    if ($(this).val() === '1') {
        $("#CityDiv").hide();
        $("#CityDivChange").show();
    }
    if ($(this).val() === '1') {
        $.ajax({
            url: urls["SetupGetStateByCountryID"],
            data: { CountryID: parseInt($(this).val()) },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value='0'>Select</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $("Select.StateDrop").html(markup);
            },
            error: function (reponse) {
                jAlert(reponse, "Error");
            },
            complete: function () {
                $("#StateDiv").show();
                $("#StateDivChange").hide();
            }
        });
    }
    else if ($(this).val() != "") {
        $.ajax({
            url: urls["SetupGetCityByCountryID"],
            data: { CountryID: parseInt($(this).val()), StateID: '0' },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value='0'>Select</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $("Select.CityDrop").html(markup);
            },
            error: function (reponse) {
                jAlert(reponse, "Error");
            },
            complete: function () {
                $("#StateDiv").hide();
                $("#StateDivChange").show();
                $("#CityDiv").show();
                $("#CityDivChange").hide();
            }
        });
    }
});
$(document).on('change', '.StateDrop', function () {
    var StateID = $(this).val();
    $.ajax({
        url: urls["SetupGetCityByCountryID"],
        data: { CountryID: 0, StateID: StateID },
        cache: false,
        type: "POST",
        success: function (data) {
            var markup = "<option value='0'>Select</option>";
            for (var x = 0; x < data.length; x++) {
                markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
            }
            $("Select.CityDrop").html(markup);
        },
        error: function (reponse) {
            jAlert(reponse, "Error");
        },
        complete: function () {
            if (StateID === "" || StateID === "0") {
                $("#CityDiv").hide();
                $("#CityDivChange").show();
            }
            else {
                $("#CityDiv").show();
                $("#CityDivChange").hide();
            }
        }
    });
});
$(document).on('change', '#Phone800', function () {
    Phone800 = $(this).val();
});
$(document).on('change', '#PhoneNumber', function () {
    PhoneNumber = $(this).val();
});
$(document).on('change', '#FaxNumber', function () {
    FaxNumber = $(this).val();
});
$(document).on('change', '#PhoneNumberUnformatted', function () {
    if ($("#PhoneNumberUnformatted").prop('checked') == true) {
        $(".phone").unmask();
        $(".phoneUSACAN").unmask();
        $(".phoneTR").unmask();
        $(".phoneFR").unmask();
        $(".phoneBEL").unmask();
        $(".phoneSWI").unmask();
        $(".phoneTS").unmask();
        $(".phoneALG").unmask();
        $(".phoneMA").unmask();

        $("#Phone800").addClass("number");
        $("#PhoneNumber").addClass("number");
        $("#FaxNumber").addClass("number");
        $(".number").maskMoney({ prefix: '', allowNegative: false, thousands: '', decimal: '', affixesStay: false, precision: 0 });

        $("#Phone800").val(Phone800);
        $("#PhoneNumber").val(PhoneNumber);
        $("#FaxNumber").val(FaxNumber);
    }
    else {
        $(".number").unmask();
        $("#Phone800").removeClass("number");
        $("#PhoneNumber").removeClass("number");
        $("#FaxNumber").removeClass("number");
        FormattedPhoneNumbers($("#SelectedCountryID").val())
    }
});
function FormattedPhoneNumbers(CountryID) {
    if ($("#PhoneNumberUnformatted").prop('checked') != true) {
        $("#Phone800").val(Phone800);
        $("#PhoneNumber").val(PhoneNumber);
        $("#FaxNumber").val(FaxNumber);
        switch (CountryID) {
            case '1': case '7':
                {
                    if (SelectedCountryID == '1' || SelectedCountryID == '7') {
                        $("#Phone800").val(Phone800);
                        $("#PhoneNumber").val(PhoneNumber);
                        $("#FaxNumber").val(FaxNumber);
                    }
                    $("#Phone800").removeAttr('class');
                    $("#Phone800").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneUSACAN');
                    $("#PhoneNumber").removeAttr('class');
                    $("#PhoneNumber").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneUSACAN');
                    $("#FaxNumber").removeAttr('class');
                    $("#FaxNumber").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneUSACAN');
                    $(".phoneUSACAN").mask("+1 (###) ###-####");
                };
                break;
            case '3':
                {
                    $("#Phone800").removeAttr('class');
                    $("#Phone800").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneTR');
                    $("#PhoneNumber").removeAttr('class');
                    $("#PhoneNumber").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneTR');
                    $("#FaxNumber").removeAttr('class');
                    $("#FaxNumber").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneTR');
                    $(".phoneTR").mask("+90 (###) ###-####");
                };
                break;
            case '5':
                {
                    $("#Phone800").removeAttr('class');
                    $("#Phone800").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneFR');
                    $("#PhoneNumber").removeAttr('class');
                    $("#PhoneNumber").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneFR');
                    $("#FaxNumber").removeAttr('class');
                    $("#FaxNumber").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneFR');
                    $(".phoneFR").mask("+33 (#) ##-##-##-##");
                };
                break
            case '8':
                {
                    $("#Phone800").removeAttr('class');
                    $("#Phone800").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneBEL');
                    $("#PhoneNumber").removeAttr('class');
                    $("#PhoneNumber").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneBEL');
                    $("#FaxNumber").removeAttr('class');
                    $("#FaxNumber").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneBEL');
                    $(".phoneBEL").mask("+32 (#) ###-##-##");
                };
                break
            case '11':
                {
                    $("#Phone800").removeAttr('class');
                    $("#Phone800").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneSWI');
                    $("#PhoneNumber").removeAttr('class');
                    $("#PhoneNumber").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneSWI');
                    $("#FaxNumber").removeAttr('class');
                    $("#FaxNumber").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneSWI');
                    $(".phoneSWI").mask("+41 (##) ###-####");
                };
                break
            case '12':
                {
                    $("#Phone800").removeAttr('class');
                    $("#Phone800").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneTS');
                    $("#PhoneNumber").removeAttr('class');
                    $("#PhoneNumber").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneTS');
                    $("#FaxNumber").removeAttr('class');
                    $("#FaxNumber").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneTS');
                    $(".phoneTS").mask("+216 (##) ###-###");
                };
                break
            case '24':
                {
                    $("#Phone800").removeAttr('class');
                    $("#Phone800").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneALG');
                    $("#PhoneNumber").removeAttr('class');
                    $("#PhoneNumber").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneALG');
                    $("#FaxNumber").removeAttr('class');
                    $("#FaxNumber").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneALG');
                    $(".phoneALG").mask("+213 (##) ###-####");
                };
                break
            case '26':
                {
                    $("#Phone800").removeAttr('class');
                    $("#Phone800").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneMA');
                    $("#PhoneNumber").removeAttr('class');
                    $("#PhoneNumber").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneMA');
                    $("#FaxNumber").removeAttr('class');
                    $("#FaxNumber").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phoneMA');
                    $(".phoneMA").mask("+212 (##) ###-####");
                };
                break
            default:
                {
                    $("#Phone800").removeAttr('class');
                    $("#Phone800").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phone');
                    $("#PhoneNumber").removeAttr('class');
                    $("#PhoneNumber").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phone');
                    $("#FaxNumber").removeAttr('class');
                    $("#FaxNumber").addClass('BankDetailsElementChange table_inputs_SmallPadding2 inpputgr form-control phone');
                    $(".phone").mask("(###) ###-####");
                };
        }
    }
}
// text element complete text 
$(document).on('input', '.QuotaTxtComplete', function () {
    if (BankTimerId == null) {
        BankAutoComElem = $(this).attr('id');
        BankAutoComElemVal = $("#" + BankAutoComElem).val();
        BankTimerId = setInterval(function () {

            var keyword = $("#" + BankAutoComElem).val();
            if (keyword == BankAutoComElemVal) {
                var PropName = "";
                if (BankAutoComElem.indexOf("BankCodeText") != -1)
                    PropName = "BankCodeText";
                if (BankAutoComElem.indexOf("BankNameText") != -1)
                    PropName = "BankNameText";

                var position = $("#" + BankAutoComElem).offset();
                position.top = position.top + $("#" + BankAutoComElem).height() + 5;
                $.ajax({
                    url: urls["SetupAutoComplete"],
                    data: { 'PropName': PropName, 'keyword': keyword },
                    type: 'POST',
                    success: function (data) {
                        $("#AutoCompleteDiv").html(data);
                        var width = $("#" + BankAutoComElem).css("width");
                        $("#AutoCompleteDiv").css("width", width);
                        $("#AutoCompleteDiv").show();
                        $("#AutoCompleteDiv").offset(position);
                    },
                    error: function (xhr) {
                        jAlert(xhr.statusText, "Error");
                    },
                    complete: function () {
                        clearInterval(BankTimerId);
                        BankTimerId = null;
                    }
                });
            }
            else
                BankAutoComElemVal = keyword;
        }, 600);
    }
});
$(document).on('click', '.QuotaAutoCompleteDivClose', function () {
    $(this).parent().parent().hide();
});
function htmlDecode(value) {
    return $('<div/>').html(value).text();
}
function AutoCompleteRowClick(key, val) {
    val = htmlDecode(val);
    $("#" + BankAutoComElem).val(val);
    if (BankAutoComElem.indexOf("BankCodeText") != -1)
        $("#" + BankAutoComElem).next().val(key);
    if (BankAutoComElem.indexOf("BankNameText") != -1)
        $("#" + BankAutoComElem).next().val(key);
    $("#AutoCompleteDiv").hide();
}

var originalClose = $.colorbox.close;
$.colorbox.close = function () {
    if ($('#BankDetailsSaveBtn').hasClass('BackColorRed')) {
        jConfirm(Messages["ClosePopUp"], Messages["ClosePopUpTitle"], function (retVal) {
            if (retVal == true) {
                $("#LoadBankDetailsForm").empty();
                LoadBankGrid();
                originalClose();
            }
        });
    }
    else {
        $("#LoadBankDetailsForm").empty();
        LoadBankGrid();
        originalClose();
    }
};
$(document).on('change', '.ElementsForValidation', function () {
    if ($(this).valid()) {
        $(this).closest("form").find("#errorMessageClient").text("");
    }
    else
        $(this).closest("form").find("#errorMessageServer").hide();
    if (BankValidationClientSideHide) {
        if ($(this).closest("form").valid()) {
            $(this).closest("form").find("#errorMessageClient").text("");
        }
    }
    else if ($(this).valid()) {
        var elements = "#" + $(this).closest("form").attr("id") + " .error";
        $(elements).not('label').each(function () {
            $(this).valid();
        });
    }
});